package com.imooc.network;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 例题2：客户端发送文件给服务器，服务端文件保存在本地
 *  * 例题2：客户端发送文件给服务器，服务端文件保存在本地
 * @Date:2021/10/19/21:54
 * @Description:
 */
public class TCPTest02 {

    @Test
    public void client() throws IOException {
        //1
        Socket socket = new Socket(InetAddress.getByName("localhost"), 9090);

        //2
        OutputStream os = socket.getOutputStream();


        //3
        FileInputStream fis = new FileInputStream(new File("中国K线.png"));


        //4
        byte[] buffer = new byte[1024];
        int len;
        while ((len =fis.read(buffer) ) != -1 ){
            os.write(buffer,0,len);
        }

        //5
        fis.close();
        os.close();
        socket.close();

    }



    @Test
    public void server() throws IOException {

        //1
        ServerSocket serverSocket = new ServerSocket(9090);
        Socket socket = serverSocket.accept();

        //2
        InputStream is = socket.getInputStream();


        //3
        FileOutputStream fileOutputStream = new FileOutputStream(new File("中国K线2.png"));

        //4
        byte[] buffer = new byte[1024];
        int len;

        while(( len= is.read(buffer)) !=-1 ){
            fileOutputStream.write(buffer,0,len);

        }

        //5
        fileOutputStream.close();
        is.close();
        socket.close();
        serverSocket.close();


    }

}
